<template>
  <div class="order-view">
    <el-dialog
      :title=title
      :visible.sync="updShow"
      width="60%"
      v-if="updShow"
      :before-close="handleClose"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <template>
        <div>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
            <el-form-item label="退货申请单编号" prop="saleBackRequestCode">
              <el-input v-model="form.saleBackRequestCode" placeholder="请输入退货申请单编号"/>
            </el-form-item>
            <el-form-item label="销售出库单编号" prop="saleOutCode">
              <el-input v-model="form.saleOutCode" placeholder="请选择销售出库单" @focus="selStockOut"/>
            </el-form-item>
            <el-form-item label="总价" prop="total">
              <el-input disabled v-model="form.total" placeholder="请输入总价"/>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <!--        detail表格-->
      <el-table :data="saleBackRequestDetailList" style="width: 100%">
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="proName"/>
        <el-table-column label="数量" align="center" prop="proNum">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.proNum"
              @change="handleInputChange(scope.row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <el-table-column label="小计" align="center">
          <template slot-scope="scope">
            {{ (scope.row.proNum * scope.row.price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['xiaoshou:saleBackRequest:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
          <el-button @click="submitForm">保 存</el-button>
          <el-button @click="closeUpd">关 闭</el-button>
        </span>
    </el-dialog>
    <el-dialog title="选择 销售出库单"
               :visible.sync="showSelStockOut"
               width="60%"
               :before-close="handleClose"
               :modal-append-to-body="false"
               :append-to-body="true">
      <el-table :data="stockOutList">
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="出库单编号" align="center" prop="stockOutCode">
          <template slot-scope="scope">
            <el-button type="text" @click="confirmStockOut(scope.row)">{{
                scope.row.stockOutCode
              }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="销售订单编号" align="center" prop="orderCode"/>
        <el-table-column label="出库类型" align="center" prop="inventoryTypeId">
          <template slot-scope="scope">
            {{ scope.row.inventoryTypeId == 2 ? "销售出库" : "其他类型" }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createDate"/>
      </el-table>
      <!--        <pagination-->
      <!--          v-show="totalSize>0"-->
      <!--          :total="totalSize"-->
      <!--          :page.sync="queryParams.pageNum"-->
      <!--          :limit.sync="queryParams.pageSize"-->
      <!--          @pagination="getStockOutList"-->
      <!--        />-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import {v4 as uuidv4} from 'uuid';
import {addSaleBackRequest, updateSaleBackRequest} from "@/api/xiaoshou/saleBackRequest";

const uuid = uuidv4();

export default {
  name: "UpdateSaleBackRequest",
  props: ["updData"],
  data() {
    return {
      saleBackRequestDetailList: [],
      title: "修改 销售退货申请",
      dialogVisible: false,
      updShow: false,
      showSelStockOut: false,
      stockOutList: {},
      stockOut: {},
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
      },
      //初始值
      saleBackRequest: this.updData,
      saleOutCode: "",
      form: this.updData,
      totalSize: 0,
      detailTotal: 0,
      // 表单校验
      rules: {
        saleBackRequestCode: [
          {required: true, message: "退货申请单编号不能为空", trigger: "blur"}
        ],
        saleOutCode: [
          {required: true, message: "销售出库单编号不能为空", trigger: "change"}
        ],
        total: [
          {required: true, message: "总价不能为空", trigger: "blur"}
        ],
      }
    };
  },
  mounted() {

  },
  watch: {
    updData() {
      this.form = this.updData;
      this.saleBackRequest = this.updData;
      this.saleOutCode = this.saleBackRequest.saleOutCode;
      this.getStockOut();
      this.getList();
    },
    saleBackRequestDetailList:{
      deep:true,
      handler(){
        this.changeTotal()
      }
    }
  },

  methods: {
    handleDelete(id) {
      // 找到要删除的对象的索引
      const index = this.saleBackRequestDetailList.findIndex(item => item.id === id);
      if (index !== -1) {
        // 使用 splice 删除对象
        this.saleBackRequestDetailList.splice(index, 1);
        this.$notify({
          title: '成功',
          message: '已成功删除商品',
          type: 'success',
        });
      } else {
        this.$notify({
          title: '错误',
          message: '未找到要删除的商品',
          type: 'error',
        });
      }
      this.changeTotal();
    },
    //改变总价
    changeTotal() {
      let totalPrice = 0;
      if (this.saleBackRequestDetailList != null) {
        this.saleBackRequestDetailList.forEach(item => {
          // 计算每个商品的价格
          item.itemPrice = (parseFloat(item.price) * parseInt(item.proNum)).toFixed(2); // 确保 price 和 num 是数字
          // 累计总价格
          totalPrice = totalPrice + parseFloat(item.itemPrice);// 使用 parseFloat 将 itemPrice 转换为数字进行累加
        });
      } else {
        totalPrice = 0;
      }
      this.form.total = (totalPrice).toFixed(2);
    },
    //修改输入框数量
    handleInputChange(row) {
      if (isNaN(row.proNum) || row.proNum <= 0) {
        this.$notify({
          title: '警告',
          message: '请输入正整数',
          type: 'warning',
        });
        row.proNum = row.inputNum; // 恢复为num
      }
      if (row.inputNum < row.proNum) {
        this.$notify({
          title: '警告',
          message: `输入的数量不能大于` + row.inputNum,
          type: 'warning',
        });
        row.proNum = row.inputNum; // 恢复为num
      }
      this.changeTotal();
    },
    /**
     * 初始查询
     * 查询销售退货申请详情列表和出库详情列表，
     * */
    getList() {
      this.loading = true;
      //退货编号条件不能改动
      this.queryParams.saleBackRequestCode = this.saleBackRequest.saleBackRequestCode;
      request({
        url: "/xiaoshou/saleBackRequestDetail/list",
        params: this.queryParams,
        methods: "get"
      }).then(response => {
        this.saleBackRequestDetailList = response.rows;
        this.detailTotal = response.total;
        this.getStockOutDetailList();
        this.updShow=true;
        this.loading = false;

      });
    },
    reset() {
      this.form = {
        saleBackRequestCode: null,
        saleOutCode: null,
        total: null
      }
      this.resetForm("form");
      this.stockOut = {};
      this.stockOutList = {};
    },
    showUpd() {
      // this.updShow = true;
    },
    closeUpd() {
      this.reset();
      this.updShow = false;
    },
    getStockOut() {
      request({
        url: "/xiaoshou/saleBackRequest/getStockOutByCode",
        params: {
          stockOutCode: this.saleBackRequest.saleOutCode
        },
        methods: "get",
      }).then(response => {
        this.stockOut = response.data;
      });
    },
    confirmStockOut(row) {
      //确认出库单就改变当前的退货详情，需要查询出库详情，然后赋给退货详情
      this.stockOut = row;
      this.form.saleOutCode = row.stockOutCode;
      this.changeOut();
      this.showSelStockOut = false;
    },
    changeOut() {
      if (this.stockOut == null) {
        return;
      }
      if (this.form.saleOutCode == this.saleBackRequest.saleOutCode) {
        this.queryParams.stockOutId = this.stockOut.id;
      }
      request({
        url: "/xiaoshou/saleBackRequest/getStockOutDetailList",
        params: this.queryParams,
        methods: "get"
      }).then(response => {
        this.stockOutDetailList = response.rows;
        //出库详情需要转换为退货详情
        this.saleBackRequestDetailList = [];
        this.stockOutDetailList.forEach(item => {
          const detail = {
            saleBackRequestCode: this.saleBackRequestCode,
            proCode: item.proCode,
            proNum: item.num,
            price: item.price,
            createBy: this.$store.getters.name,
          };
          this.saleBackRequestDetailList.push(detail);
        });
        this.saleBackRequestDetailList.forEach(item => {
          const stockItem = this.stockOutDetailList.find(item1 => item.proCode === item1.proCode);
          if (stockItem) {
            item.inputNum = stockItem.num; // 如果找到了对应商品，赋值
          } else {
            item.inputNum = item.proNum; // 如果没有找到对应商品，则恢复为原有数量
          }
        });
      });
    },
    getStockOutDetailList() {
      if (this.stockOut == null) {
        return;
      }
      if (this.form.saleOutCode == this.saleBackRequest.saleOutCode) {
        this.queryParams.stockOutId = this.stockOut.id;
      }
      request({
        url: "/xiaoshou/saleBackRequest/getStockOutDetailList",
        params: this.queryParams,
        methods: "get"
      }).then(response => {
        this.stockOutDetailList = response.rows;
        if (this.form.saleOutCode != this.saleOutCode) {
          //出库详情需要转换为退货详情
          this.saleBackRequestDetailList = [];
          this.stockOutDetailList.forEach(item => {
            const detail = {
              saleBackRequestCode: this.saleBackRequestCode,
              proCode: item.proCode,
              proNum: item.num,
              price: item.price,
              createBy: this.$store.getters.name,
            };
            this.saleBackRequestDetailList.push(detail);
          });
        }
        this.saleBackRequestDetailList.forEach(item => {
          const stockItem = this.stockOutDetailList.find(item1 => item.proCode === item1.proCode);
          if (stockItem) {
            item.inputNum = stockItem.num; // 如果找到了对应商品，赋值
          } else {
            item.inputNum = item.proNum; // 如果没有找到对应商品，则恢复为原有数量
          }
        });
      });
    },
    handleClose(done) {
      done();
    },
    //获取出库单列表
    getStockOutList() {
      this.loading = true;
      request({
        url: "/xiaoshou/saleBackRequest/getStockOutList",
        methods: "get",
        params: this.queryParams
      }).then(response => {
        this.stockOutList = response.rows;
        this.totalSize = response.total;
        this.loading = false;
      });
    },
    //弹出出库单列表
    selStockOut() {
      this.getStockOutList();
      this.showSelStockOut = true;
    },
    submitForm() {
      this.form.updateBy=this.$store.getters.name;
      if (this.form.id != null) {
        updateSaleBackRequest(this.form).then(response => {
          //修改申请之后需要修改详情的关联单据编号
          this.saleBackRequestDetailList.forEach(item => {
            item.saleBackRequestCode = this.form.saleBackRequestCode;
          })
          //还需要修改详情
          //传递list
          request({
            url: "/xiaoshou/saleBackRequestDetail/addSaleBackRequestDetail",
            data: this.saleBackRequestDetailList,
            method: "post"
          }).then(res => {
            this.$modal.msgSuccess("修改成功");
          });
          this.$emit("updList");
          this.updShow = false;
        });
      } else {
        this.form.createBy = this.$store.getters.name;
        request({
          url: "/xiaoshou/saleBackRequest/addSaleBackRequest",
          data: this.form,
          method: "post",
        }).then(res => {
          this.$modal.msgSuccess("新增成功");
          this.$refs.sod.addDetails();
          this.$emit("updList");
          this.updShow = false;
          this.reset();
        });
      }
    },
    cancel() {
      this.showSelStockOut = false;
    }
  },
};
</script>
